import {Card, DatePicker, message, Modal} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ActionType} from '@ant-design/pro-table';
import type {TableListItem} from './data.d';
import {queryGridProfit, queryGridProfitCurve, queryGridProfitCurveSum} from './service';
import {
  columnsSorter,
  columnToColumnsState,
  empty,
  formatDate,
  getNowFormatDate,
  NumberDiv,
  NumberDivide, reRedAndGreen
} from "@/utils/function";
import {queryUse} from "@/utils/service";
import {getSelectList} from "@/pages/BTCList/getSelectList";
import {round} from "mathjs";
import {OrderTrade} from "@/pages/Futuers/data";
import "@/components/Echarts/EchartsOne";
import EchartsOne from "@/components/Echarts/EchartsOne";
import cloneDeep from 'lodash/cloneDeep';

let sorterGridProfit: any = null;
let dataCopyGridProfit: any = null;
let ids: any = [];

const GridProfit: React.FC = () => {
  const [dataTable, setDataTable] = useState<any>(null);
  const [dateS, setDateS] = useState<any>(null);
  const [series, setSeries] = useState<any>(null);

  // @ts-ignore
  let columns: any[] = [

    {
      title: "交易对",
      dataIndex: 'symbol',
      key: 'symbol',
      fixed: 'left',
      width: 120,
    },
    {
      title: "用户名称",
      dataIndex: 'name',
      fixed: 'left',
      key: 'name',
      width: 120,
    },
    {
      title: "当前价格",
      width: 120,
      dataIndex: 'currentPrice',
      key: 'currentPrice',
      sorter: true,
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
  {
      title: "总盈亏",
      width: 120,
      dataIndex: 'totalProfit',
      key: 'totalProfit',
      sorter: true,
      renderText: (val: string | number) => reRedAndGreen(NumberDiv(val, 1, 4))
    },
    {
      title: "持仓数量",
      width: 120,
      dataIndex: 'positionQty',
      key: 'positionQty',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
    {
      title: "持仓成本",
      width: 120,
      dataIndex: 'positionPrincipal',
      key: 'positionPrincipal',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
    {
      title: "持仓盈亏",
      width: 120,
      sorter: true,
      dataIndex: 'positionPrifit',
      key: 'positionPrifit',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },

    {
      title: "开始时间",
      width: 120,
      dataIndex: 'start',
      key: 'start',
      renderText: (val: string) => formatDate(val, false)
    },
    {
      title: "结束时间",
      width: 120,
      dataIndex: 'end',
      key: 'end',
      renderText: (val: string) => formatDate(val, false)
    },
    // {
    //   title: "买入数量",
    //   width: 120,
    //   dataIndex: 'buyQty',
    //   key: 'buyQty',
    //   renderText: (val: string | number) => NumberDiv(val, 1, 4)
    // },
    // {
    //   title: "买入金额",
    //   width: 120,
    //   dataIndex: 'buyAmount',
    //   key: 'buyAmount',
    //   renderText: (val: string | number) => NumberDiv(val, 1, 4)
    // },
    // {
    //   title: "卖出数量",
    //   width: 120,
    //   dataIndex: 'sellQty',
    //   key: 'sellQty',
    //   renderText: (val: string | number) => NumberDiv(val, 1, 4)
    // },
    // {
    //   title: "卖出金额",
    //   width: 120,
    //   dataIndex: 'sellAmount',
    //   key: 'sellAmount',
    //   renderText: (val: string | number) => NumberDiv(val, 1, 4)
    // },
    {
      title: "买卖收益",
      width: 120,
      dataIndex: 'profit',
      key: 'profit',
      sorter: true,
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },

    {
      title: "手续费",
      sorter: true,
      width: 120,
      dataIndex: 'commission',
      key: 'commission',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
    {
      title: "手续费组成",
      width: 150,
      dataIndex: 'commissionMap',
      key: 'commissionMap',
      renderText: (val: {}) => {
        let valText = [];
        for (let i in val) {
          let item = val[i];
          valText.push(<div>{i + " : " + round(Number(item), 4)}</div>);
        }
        return valText;
      }
    },
    {
      title: "资金费用",
      width: 120,
      dataIndex: 'arbitrageProfit',
      key: 'arbitrageProfit',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
    {
      title: "投资金额(持仓)",
      width: 120,
      dataIndex: 'invest',
      key: 'invest',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
    {
      title: "指数价格",
      width: 120,
      dataIndex: 'price',
      key: 'price',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
    {
      title: "操作",
      search: false,
      width: 280,
      render: (_: any, record: any) => {
        // if (record.orderMethod === "close") {
        if (record["symbol"] === "合计") {
          return <div>
            <a href="javascript:void(0);" onClick={async () => {
              await openLinesSum(record)
            }}>
              收益曲线
            </a>{' '}
          </div>
        }
        return <div>
          <a href="javascript:void(0);" onClick={async () => {
            await openLines(record)
          }}>
            收益曲线
          </a>{' '}
        </div>
        // }
      }
    }
  ];
  columnsSorter("GridProfit网格策略收益统计", columns);
  const [col, setCol] = useState<any>(columnToColumnsState(columns));

  const [lastDay, setLastDay] = useState<any>("");
  const [createDetailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
  const [createTradeModal, handleTradeModal] = useState<OrderTrade>({
    symbol: null,
  });
  const actionRef = useRef<ActionType>();

  const openLines = async (record: any) => {
    const msg = await queryGridProfitCurve(record.id);
    let data = queryUse(msg);
    if (!empty(data)) {

      let dataLines: any = {
        timeList: [],
        profitList: [],
      }
      for (let dataKey in data) {
        dataLines.timeList.push(dataKey);
        dataLines.profitList.push(data[dataKey]);
      }
      let lastDay = <span>&nbsp;&nbsp;&nbsp;{" 最后更新: " + dataLines.timeList[dataLines.timeList.length - 1] +
      "时"}&nbsp;&nbsp;&nbsp;&nbsp;{"收益: " + NumberDivide(dataLines.profitList[dataLines.profitList.length - 1], 2)}</span>;

      let series = {
        // title: {
        //   text: '燃尽图'
        // },
        tooltip: {
          trigger: 'axis',
          formatter(params: any[]) {
            let result = params[0].name + "时";
            params.forEach(function (item) {
              result += '<br/>';
              if (item.seriesName === '收益') {
                if (item.value > 0) {
                  result +=
                    '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' +
                    'rgba(222,44,84,0.3)' +
                    '"></span>';
                } else {
                  result +=
                    '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' +
                    'rgba(131,210,39,0.3)' +
                    '"></span>';
                }
              }

              result += ` ${item.seriesName}：`;

              if (item.seriesName === '收益') {
                result += (isNaN(item.value) ? 0 : NumberDivide(item.value, 2));
              }
            });
            return result;
          },
        },
        // toolbox: {
        //   feature: {
        //     saveAsImage: {}
        //   }
        // },
        legend: {
          data: ['收益']
        },
        xAxis: {
          type: 'category',
          axisTick: {
            show: false,
          },
          axisLabel: {
            showMaxLabel: true,
            // normal
            color: '#333333',
            showMinLabel: true,
            fontSize: 13,
            padding: [10, 4, 10, 4],
          },

          // boundaryGap: ['20%', '20%'],
          axisLine: {
            lineStyle: {
              color: 'rgba(155,155,155,0.7)',
              width: 1,
              type: 'dashed',
            },
          },
          position: 'bottom',
          // splitNumber:8,
          data: dataLines.timeList,
        },
        dataZoom: [
          {
            show: true,
            xAxisIndex: 0,
            type: 'inside',
            start: 0,
            end: 100,
            // minValueSpan: 10,
          },
        ],
        yAxis: {
          type: 'value',
          position: 'right',
        },
        series: [
          {
            name: '收益',
            data: dataLines.profitList,
            type: 'line',
            showSymbol: false,
            lineStyle: {
              width: 1.5,
            },
          },
        ]
      }
      setSeries(series);
      setLastDay(lastDay);
      handleTradeModal({symbol: record.symbol,})
      handleDetailModalVisible(true);
    } else {
      message.error("暂无数据")
    }

  }
  const openLinesSum = async (record: any) => {
    const msg = await queryGridProfitCurveSum(ids);
    // debugger
    let data = queryUse(msg);
    if (!empty(data)) {

      let dataLines: any = {
        timeList: [],
        profitList: [],
      }
      for (let dataKey in data) {
        dataLines.timeList.push(dataKey);
        dataLines.profitList.push(data[dataKey]);
      }
      let lastDay = <span>&nbsp;&nbsp;&nbsp;{" 最后更新: " + dataLines.timeList[dataLines.timeList.length - 1] +
      "时"}&nbsp;&nbsp;&nbsp;&nbsp;{"收益: " + NumberDivide(dataLines.profitList[dataLines.profitList.length - 1], 2)}</span>;

      let series = {
        // title: {
        //   text: '燃尽图'
        // },
        tooltip: {
          trigger: 'axis',
          formatter(params: any[]) {
            let result = params[0].name + "时";
            params.forEach(function (item) {
              result += '<br/>';
              if (item.seriesName === '收益') {
                if (item.value > 0) {
                  result +=
                    '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' +
                    'rgba(222,44,84,0.3)' +
                    '"></span>';
                } else {
                  result +=
                    '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' +
                    'rgba(131,210,39,0.3)' +
                    '"></span>';
                }
              }

              result += ` ${item.seriesName}：`;

              if (item.seriesName === '收益') {
                result += (isNaN(item.value) ? 0 : NumberDivide(item.value, 2));
              }
            });
            return result;
          },
        },
        // toolbox: {
        //   feature: {
        //     saveAsImage: {}
        //   }
        // },
        legend: {
          data: ['收益']
        },
        xAxis: {
          type: 'category',
          axisTick: {
            show: false,
          },
          axisLabel: {
            showMaxLabel: true,
            // normal
            color: '#333333',
            showMinLabel: true,
            fontSize: 13,
            padding: [10, 4, 10, 4],
          },

          // boundaryGap: ['20%', '20%'],
          axisLine: {
            lineStyle: {
              color: 'rgba(155,155,155,0.7)',
              width: 1,
              type: 'dashed',
            },
          },
          position: 'bottom',
          // splitNumber:8,
          data: dataLines.timeList,
        },
        dataZoom: [
          {
            show: true,
            xAxisIndex: 0,
            type: 'inside',
            start: 0,
            end: 100,
            // minValueSpan: 10,
          },
        ],
        yAxis: {
          type: 'value',
          position: 'right',
        },
        series: [
          {
            name: '收益',
            data: dataLines.profitList,
            type: 'line',
            showSymbol: false,
            lineStyle: {
              width: 1.5,
            },
          },
        ]
      }
      setSeries(series);
      setLastDay(lastDay);
      handleTradeModal({symbol: record.symbol,})
      handleDetailModalVisible(true);
    } else {
      message.error("暂无数据")
    }

  }


  useEffect(() => {
    getSelectList("2", "GridProfit", actionRef).then(
      (selectList: React.ReactNode) => {
        setDataTable(
          <ProTable<TableListItem>
            headerTitle={""}
            // rowKey="key"
            bordered
            actionRef={actionRef}
            columnsStateMap={col}
            onColumnsStateChange={(e) => {
              if (!empty(e)) {
                localStorage.setItem("GridProfit网格策略收益统计", JSON.stringify(e));
                setCol(e);
              }
            }}
            toolBarRender={() => [
              // <div>合计盈亏：{}</div>,
              <div>{selectList}</div>,
              <div>
                选择起始日期:&nbsp;&nbsp;
                <DatePicker
                  // showTime
                  format="YYYY-MM-DD"
                  placeholder="请选择"
                  style={{width: 200, margin: 20, marginLeft: 10}}
                  onChange={(e) => {
                    setDateS(getNowFormatDate((e ? e : null)));
                  }}
                />
              </div>,
            ]}
            params={{date: dateS}}
            pagination={false}
            scroll={{x: 1200, y: 666}}
            search={false}
            request={async (params = {}, sort: any, filter: any,) => {
              // console.log(params.toString());
              let data = [];

              //dataCopy
              if (sorterGridProfit !== null && sort !== sorterGridProfit) {
                data = cloneDeep(dataCopyGridProfit);
                sorterGridProfit = (sort);
              } else {
                const msg = await queryGridProfit(params.date);
                data = queryUse(msg);
                dataCopyGridProfit = cloneDeep(data);
                sorterGridProfit = (sort);
              }

              //sort
              if (!empty(sort)) {
                const dataSort = (data: { sort: (arg0: (a: any, b: any) => void) => any; }, dataIndex: string, fg: boolean) =>
                  data.sort((a, b) => {
                    return fg ? (a[dataIndex] - b[dataIndex]) : (b[dataIndex] - a[dataIndex]);
                  })
                let dataIndex = '';
                let fg = true;
                for (let sortKey in sort) {
                  dataIndex = sortKey;
                  fg = (sort[sortKey] === 'ascend');
                }
                data = dataSort(data, dataIndex, fg);
              }
              ids = [];
              //sum 'commission','arbitrageProfit','invest',
              let sumItem: any = {
                symbol: "合计",
                profit: 0,
                totalProfit: 0,
                commission: 0,
                arbitrageProfit: 0,
                positionPrifit: 0,
                positionPrincipal: 0,
                invest: 0,
              }
              for (let i = 0; i < data.length; i++) {
                const item = data[i];
                sumItem.profit += (item.profit ? item.profit : 0);
                sumItem.totalProfit += (item.totalProfit ? item.totalProfit : 0);
                sumItem.commission += (item.commission ? item.commission : 0);
                sumItem.arbitrageProfit += (item.arbitrageProfit ? item.arbitrageProfit : 0);
                if(!item.end){
                  sumItem.invest += (item.invest ? item.invest : 0);
                }
                sumItem.positionPrifit += (item.positionPrifit ? item.positionPrifit : 0);
                sumItem.positionPrincipal += (item.positionPrincipal ? item.positionPrincipal : 0);
                ids.push(item.id)
              }
              data.unshift(sumItem)

              if (data) {
                return {
                  data: data,
                  // success 请返回 true，
                  // 不然 table 会停止解析数据，即使有数据
                  success: true,
                  // 不传会使用 data 的长度，如果是分页一定要传
                  // total: number,
                };
              } else {
                return {
                  data: [],
                  success: false,
                };
              }
            }}
            columns={columns}
          />
        )
      })
  }, [dateS,col])


  return (
    <PageContainer>
      <Card>
        {dataTable}
        {/**
         *@modal
         */}
        <Modal
          destroyOnClose
          title={<div>{"交易对 " + createTradeModal.symbol + " 收益曲线 "}{lastDay}</div>}
          width="80%"
          centered
          footer={false}
          onOk={() => handleDetailModalVisible(false)}
          onCancel={() => handleDetailModalVisible(false)}
          visible={createDetailModalVisible}
        >
          <EchartsOne chartId={"GridProfit网格策略收益统计"} series={series}/>
          {/*<FutuersDetailList symbol={createTradeModal.symbol} group={createTradeModal.group}/>*/}

        </Modal>
      </Card>
    </PageContainer>
  );
};

export default GridProfit;
